package com.web.webstart.base.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.web.webstart.base.constant.ConfigVariable;
import org.yaml.snakeyaml.Yaml;

public class BaiduMapUtil {
	
	//百度AK
	public static String baiduMapAK=ConfigVariable.baiduMapAK;
	//根据地址获取经纬度的请求地址
	public static String  baiduMapUrlGeocoder=ConfigVariable.baiduMapUrlGeocoder;
  
    /** 
     * 返回输入地址的经纬度坐标 
     * 
     */ 
	/**
	 * @Title: getGeocoderLatitude
	 * @Description: 根据地址，获得经纬度坐标
	 * @param address 地址
	 * @return  key lng(经度),lat(纬度) 
	 * @throws
	 */
    public static Map<String,String> getGeocoderLatitude(String address){
        BufferedReader in = null;
        try {  
            //将地址转换成utf-8的16进制  
            address = URLEncoder.encode(address, "UTF-8");  
            URL tirc = new URL(baiduMapUrlGeocoder+"?address="+ address +"&output=json&ak="+ baiduMapAK);  
  
  
            in = new BufferedReader(new InputStreamReader(tirc.openStream(),"UTF-8"));  
            String res;  
            StringBuilder sb = new StringBuilder("");  
            while((res = in.readLine())!=null){  
                sb.append(res.trim());  
            }  
            String str = sb.toString();  
            Map<String,String> map = null;  
            if(StringUtils.isNotEmpty(str)){  
                int lngStart = str.indexOf("lng\":");  
                int lngEnd = str.indexOf(",\"lat");  
                int latEnd = str.indexOf("},\"precise");  
                if(lngStart > 0 && lngEnd > 0 && latEnd > 0){  
                    String lng = str.substring(lngStart+5, lngEnd);  
                    String lat = str.substring(lngEnd+7, latEnd);  
                    map = new HashMap<String,String>();  
                    map.put("lng", lng);  
                    map.put("lat", lat);  
                    return map;  
                }  
            }  
        }catch (Exception e) {  
            e.printStackTrace();  
        }finally{  
            try {  
                in.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return null;  
    }  
	      
	   

}
